package com.dcy.znoa.common.filter;

import com.alibaba.fastjson.JSONObject;
import com.dcy.znoa.common.bean.Result;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.domain.OperSession;
import com.dcy.znoa.service.software.SessionService;
import com.dcy.znoa.common.util.http.HttpRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class LoginFilter implements Filter {
    private final Logger LOGGER = Logger.getLogger(getClass());

    public static final String HTTP_ATTR_SESSION_KEY = "_sessionObject";
    public static final String HTTP_ATTR_USER_KEY = "_userObject";
    private static final String HTTP_ATTR_SESSION_ID = "sessionId";
    private static final String HTTP_ATTR_SESSION_TOKEN = "token";

    @Autowired
    private SessionService sessionService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //to do nothing
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        long sid = -1L;
        long sidQk = HttpRequestUtils.getLongParameter(httpServletRequest, HTTP_ATTR_SESSION_ID);
        long sidPy = -1L;
        if(StringUtils.isNumeric(httpServletRequest.getParameter(HTTP_ATTR_SESSION_ID))){
            sidPy = Long.valueOf(httpServletRequest.getParameter(HTTP_ATTR_SESSION_ID));
        }
//        long sidPy = Long.valueOf(httpServletRequest.getParameter(HTTP_ATTR_SESSION_ID));//pengyu modify
        if(sidQk>0){
            sid = sidQk;
        }else if (sidPy >0){
            sid = sidPy;
        }
        String token = httpServletRequest.getParameter(HTTP_ATTR_SESSION_TOKEN);

        String path = httpServletRequest.getServletPath();

        if (sid != -1) {
            try {
                final OperSession session = sessionService.touchSession(sid, token);
                httpServletRequest.setAttribute(HTTP_ATTR_SESSION_KEY, session);
                if (session.getOper() == null) {
                    log.info("!!!!!!!!!!!!!!!!!!!!session user is empty");
                }
                httpServletRequest.setAttribute(HTTP_ATTR_USER_KEY, session.getOper());
            } catch (BusinessException e) {
                // 重复登录，返回错误码
                httpServletResponse.setContentType("text/plain;charset=UTF-8");
                //TODO 以后需要修改为SSO里面的错误码（需要协商）
//                Result result = new Result(String.valueOf(e.getErrorCode()), e.getErrorMsg(), Result.Status.ERROR);
                JsonCommon result = new JsonCommon(e.getErrorCode(), e.getErrorMsg());
                httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
                httpServletResponse.getWriter().write(JSONObject.toJSONString(result));
                return ;
            }
        }
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        chain.doFilter(httpServletRequest, httpServletResponse);
    }

    @Override
    public void destroy() {
        //to do nothing
    }
}
